package com.example.aop;

import com.example.redis.CounterLimit;
import com.example.redis.SlidingLimit;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author syg
 * @description
 * @date 2021/12/27 14:44
 */
@Slf4j
@Aspect
@Component
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class LimitAspect {

    @Autowired
    CounterLimit counterLimit;
    @Autowired
    SlidingLimit slidingLimit;

    @Before("@annotation(com.example.aop.CounterLimitAnno)")
    public void beforeLimit1(JoinPoint joinPoint) throws Exception {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        CounterLimitAnno counterLimitAnno = method.getAnnotation(CounterLimitAnno.class);
        String key = counterLimitAnno.limitKey();
        int limit = counterLimitAnno.limit();
        Boolean exceededLimit = counterLimit.distributedLimit(key, String.valueOf(limit));
        if(!exceededLimit) {
            throw new RuntimeException("exceeded limit");
        }
    }

    @Before("@annotation(com.example.aop.SlidingLimitAnno)")
    public void beforeLimit2(JoinPoint joinPoint) throws Exception {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        SlidingLimitAnno slidingLimitAnno = method.getAnnotation(SlidingLimitAnno.class);
        String key = slidingLimitAnno.limitKey();
        int timewin = slidingLimitAnno.timeWin();
        int maxCount = slidingLimitAnno.maxCount();
        Boolean exceededLimit = slidingLimit.isActionAllow(key, key, timewin, maxCount);
        if(!exceededLimit) {
            throw new RuntimeException("exceeded limit");
        }
    }

}